/*
  +----------------------------------------------------------------------+
  | PHP Version 7                                                        |
  +----------------------------------------------------------------------+
  | Copyright (c) 1997-2018 The PHP Group                                |
  +----------------------------------------------------------------------+
  | This source file is subject to version 3.01 of the PHP license,      |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.php.net/license/3_01.txt                                  |
  | If you did not receive a copy of the PHP license and are unable to   |
  | obtain it through the world-wide-web, please send a note to          |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Author:                                                              |
  +----------------------------------------------------------------------+
*/

/* $Id$ */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_iwonmo.h"
#include "zend.h"
#include "zend_API.h"
#include "zend_exceptions.h"
#include "zend_operators.h"
#include "zend_constants.h"
#include "zend_ini.h"
#include "zend_interfaces.h"
#include "zend_closures.h"
#include "zend_generators.h"
#include "zend_extensions.h"
#include "zend_builtin_functions.h"
#include "zend_smart_str.h"
#include <sys/time.h>
#include <time.h>
#include "mmap.h"
#include "other.h"

/* If you declare any globals in php_iwonmo.h uncomment this:
ZEND_DECLARE_MODULE_GLOBALS(iwonmo)
*/

/* 定义方法别名 */
#define IO_FUNCTION(mname) PHP_FUNCTION(mname)
#define IO_METHOD(classname, name) PHP_METHOD(classname, name)

/* True global resources - no need for thread safety here */
static int le_iwonmo;
apc_cache_t *cache;
/* PHP新版本回调函数结构体 */
typedef struct _callfun
{
	zend_fcall_info fci;
	zend_fcall_info_cache fci_cache;
} callfun;

/* 定义key结构体 */
typedef struct _key_info
{
	char *keyName;	 /* key名 */
	uint keyLength;	 /* 长度 */
	ulong time;		 /* 存入时间(毫秒) */
	uint expireTime; /* 等待毫秒数 */
} KEYINFO, *KeyInfo;

/* 定义链表 */
typedef struct _key_list
{
	KEYINFO keyinfo;		/*key结构体*/
	struct _key_list *next; /* 后指针 */
} KEYLIST, *KeyList;

KeyList keylist; /* 全局的列表变量 */

/**
 * 拼接字符串
 * 
 * @description: iwonmo
 * @Date: 2021-06-29 16:49:00
 * @param {zend_string} *zs1
 * @param {zend_string} *zs2
 * @param {zend_string} *zs3
 * @return {*}
 */
static zend_string *io_str_add(zend_string *zs1, zend_string *zs2, zend_string *zs3)
{
	zend_string *ret;
	size_t len = ZSTR_LEN(zs2);
	zs1 = zend_string_extend(zs2, len + ZSTR_LEN(zs3), 0);
	memcpy(ZSTR_VAL(zs1) + len, ZSTR_VAL(zs3), ZSTR_LEN(zs3) + 1);
	ZVAL_NEW_STR(&ret, zs1);
	return ret;
}

/**
 * 获取一个key值 文件名+当前调用函数名 （弃用）
 * 
 * @description: iwonmo
 * @Date: 2021-06-29 16:48:53
 * @param {*}
 * @return {*}
 */
zend_string *io_get_key()
{
	zend_execute_data *ptr, *call = NULL;
	zend_object *object;
	zend_function *func;
	zend_string *function_name;
	zend_string *filename;
	zend_string *key;

	if (!(ptr = EG(current_execute_data)))
	{
		return;
	}
	if (!ptr->func || !ZEND_USER_CODE(ptr->func->common.type))
	{
		call = ptr;
		ptr = ptr->prev_execute_data;
	}
	if (ptr)
	{
		ptr = zend_generator_check_placeholder_frame(ptr);
		call = ptr;
		while (!ptr->func->op_array.filename)
			ptr = ptr->prev_execute_data;
		filename = ptr->func->op_array.filename;
		object = (call && (Z_TYPE(call->This) == IS_OBJECT)) ? Z_OBJ(call->This) : NULL;
		while (!call->func)
			call = call->prev_execute_data;
		func = call->func;
		function_name = (func->common.scope &&
						 func->common.scope->trait_aliases)
							? zend_resolve_method_name(
								  (object ? object->ce : func->common.scope), func)
							: func->common.function_name;
		if (!function_name)
		{
			function_name = ZSTR_KNOWN(ZEND_STR_UNKNOWN);
		}
	}
	key = io_str_add(key, filename, function_name);
	return key;
}

/**
 * 执行匿名闭包函数
 * 
 * @description: iwonmo
 * @Date: 2021-06-29 16:48:39
 * @param {callfun} *context
 * @return {*}
 */
int io_callback(callfun *context)
{
	zval retval;
	ZVAL_NULL(&retval);
	context->fci.retval = &retval;
	context->fci.no_separation = 0;
	int ret = zend_call_function(&context->fci, &context->fci_cache TSRMLS_CC);
	zval_ptr_dtor(&retval);
	return ret;
}

/**
 * 获取毫秒时间
 * 
 * @description: iwonmo
 * @Date: 2021-06-29 16:48:32
 * @param {*}
 * @return {*}
 */
ulong io_m_time()
{
	struct timeval t;
	gettimeofday(&t, NULL);
	return ((ulong)t.tv_sec) * 1000 + (ulong)t.tv_usec / 1000;
}

/**
 * 调试打印key
 * 
 * @description: iwonmo
 * @Date: 2021-06-29 16:48:26
 * @param {KeyInfo} k
 * @return {*}
 */
void io_debug_keyinfo(KeyInfo k)
{
	php_printf("-----------------------------\n");
	php_printf("\033[40;33mkeyName：%s\n\033[0m", k->keyName);
	php_printf("\033[40;34mkeyLength：%d\n\033[0m", k->keyLength);
	php_printf("\033[40;35mtime：%ld\n\033[0m", k->time);
	php_printf("\033[40;36mexpireTime：%d\n\033[0m", k->expireTime);
	php_printf("-----------------------------\n");
}

/**
 * 调试打印整个链表
 * 
 * @description: iwonmo
 * @Date: 2021-06-29 16:48:19
 * @param {*}
 * @return {*}
 */
void io_debug_keylist()
{
	KeyList t1;
	t1 = keylist->next;
	int i = 0;
	while (t1)
	{
		php_printf("\n第 [%d] 条数据\n", ++i);
		io_debug_keyinfo(&t1->keyinfo);
		t1 = t1->next;
	}
	return;
}

/**
 * 插入链表
 * 
 * @description: iwonmo
 * @Date: 2021-06-29 16:47:55
 * @param {KeyInfo} keyinfo 结构体
 * @param {BOOL} head 是否插入到头部
 * @return {*}
 */
int io_insert_key_list(KeyInfo keyinfo, BOOL head)
{
	KeyList t1, t2 = keylist;
	/* 重新整个结构 */
	KEYINFO k1;
	k1.keyName = keyinfo->keyName;
	k1.keyLength = keyinfo->keyLength;
	k1.time = keyinfo->time;
	k1.expireTime = keyinfo->expireTime;
	t1 = emalloc(sizeof(KEYLIST));
	memset(t1, 0, sizeof(KEYLIST));
	if (!t1)
		return -1;
	t1->keyinfo = k1;
	if (head)
	{
		t1->next = keylist->next;
		keylist->next = t1;
	}
	else
	{
		while (keylist->next)
			keylist = keylist->next;
		keylist->next = t1;
		keylist = t2;
	}
	return 0;
}

/* {{{ PHP_INI
 */
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
    STD_PHP_INI_ENTRY("iwonmo.global_value",      "42", PHP_INI_ALL, OnUpdateLong, global_value, zend_iwonmo_globals, iwonmo_globals)
    STD_PHP_INI_ENTRY("iwonmo.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_iwonmo_globals, iwonmo_globals)
PHP_INI_END()
*/
/* }}} */

/* Remove the following function when you have successfully modified config.m4
   so that your module can be compiled into PHP, it exists only for testing
   purposes. */

/* Every user-visible function in PHP should document itself in the source */
/* {{{ proto string confirm_iwonmo_compiled(string arg)
   Return a string to confirm that the module is compiled in */
PHP_FUNCTION(confirm_iwonmo_compiled)
{
	char *arg = NULL;
	size_t arg_len, len;
	zend_string *strg;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &arg, &arg_len) == FAILURE)
	{
		return;
	}

	strg = strpprintf(0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "iwonmo", arg);

	RETURN_STR(strg);
}
/* }}} */
/* The previous line is meant for vim and emacs, so it can correctly fold and
   unfold functions in source code. See the corresponding marks just before
   function definition, where the functions purpose is also documented. Please
   follow this convention for the convenience of others editing your code.
*/

/* {{{ php_iwonmo_init_globals
 */
/* Uncomment this function if you have INI entries
static void php_iwonmo_init_globals(zend_iwonmo_globals *iwonmo_globals)
{
	iwonmo_globals->global_value = 0;
	iwonmo_globals->global_string = NULL;
}
*/
/* }}} */

/* {{{ PHP_MINIT_FUNCTION
 */
PHP_MINIT_FUNCTION(iwonmo)
{
	/* If you have INI entries, uncomment these lines
	REGISTER_INI_ENTRIES();
	*/

	/* 对链表进行初始化 */
	keylist = emalloc(sizeof(KEYLIST));
	memset(keylist, 0, sizeof(KEYLIST));

	/* 初始化内存空间 */
	apc_module_init();
	cache = apc_cache_create(1000, 3600);
	io_mutex_init();
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MSHUTDOWN_FUNCTION
 */
PHP_MSHUTDOWN_FUNCTION(iwonmo)
{
	/* uncomment this line if you have INI entries
	UNREGISTER_INI_ENTRIES();
	*/
	php_printf("\n释放锁\n");
	free(cache);
	apc_sma_cleanup();
	io_mutex_cleanup();
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
 */
PHP_RINIT_FUNCTION(iwonmo)
{
#if defined(COMPILE_DL_IWONMO) && defined(ZTS)
	ZEND_TSRMLS_CACHE_UPDATE();
#endif
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
 */
PHP_RSHUTDOWN_FUNCTION(iwonmo)
{
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(iwonmo)
{
	php_info_print_table_start();
	php_info_print_table_header(2, "iwonmo support", "enabled");
	php_info_print_table_end();

	/* Remove comments if you have entries in php.ini
	DISPLAY_INI_ENTRIES();
	*/
}
/* }}} */

/**
 * 获取毫秒
 * 
 * @description: iwonmo
 * @Date: 2021-06-29 16:47:18
 * @param {*}
 * @return {*}
 */
IO_FUNCTION(io_mtime)
{
	RETVAL_LONG(io_m_time());
}

/**
 * 数字转字符串
 * 
 * @Author: iwonmo
 * @Date: 2021-06-30 15:33:10
 * @Param: 
 * @Return: 
 * @param {int} number
 */
char *intoc(int number)
{
	char *s = (char *)malloc(sizeof(int));
	snprintf(s, sizeof(s), "%d", number);
	return s;
}

/**
 * 循环字符串
 * 
 * @Author: iwonmo
 * @Date: 2021-07-14 15:33:10
 * @Param: 
 * @Return: 
 * @param {char*} str
 */
IO_FUNCTION(io_looptext)
{
	zend_long num;
	char *str;
	size_t str_len;
	char *buffer;
	if (zend_parse_parameters(ZEND_NUM_ARGS(), "ls", &num, &str, &str_len) == FAILURE)
	{
		RETURN_BOOL(FALSE);
	}
	if (num < 0)
		RETURN_BOOL(FALSE);
	if (num == 0)
		RETURN_STRING("");
	int max = str_len * num + 1;
	buffer = (char *)malloc(max);
	if (buffer == NULL)
		RETURN_BOOL(FALSE);
	int i = 0;
	for (i = 0; i < num; i++)
		strcpy(buffer + i * str_len, str);
	RETURN_STRINGL((char *)buffer, max);
}

/**
 * 间隔函数
 * 
 * @description: iwonmo
 * @Date: 2021-06-29 16:45:45
 * @param {int} key 1-2000 插槽Index
 * @param {function} 闭包函数
 * @param {long} 过期时间（毫秒）
 * @return {*}
 */
IO_FUNCTION(io_interval)
{
	callfun context;
	int key;
	int expireTime = 500;
	KeyInfo keyinfo;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|fl", &key, &context.fci, &context.fci_cache, &expireTime) == FAILURE)
	{
		return;
	}

	key -= 1;

	if (expireTime == 0)
		expireTime = 500;
	char *Mem = getMem(intoc(key));
	pthread_mutex_t *mutex = (pthread_mutex_t *)Mem;
	pthread_cond_t *cond = getCond(Mem);
	io_mutex_lock(mutex, cond);
	ulong t = mtime();
	int expire_time = apc_cache_insert(cache, key, expireTime);
	/*
		如果当前KEY已经存在。需要判断是否有匿名函数传递
		当存在匿名函数则先执行匿名函数，如果不存在匿名函数
		等待以后则直接返回
	 */
	if (expire_time > 1)
	{
		if (context.fci.size == sizeof(zend_fcall_info))
		{
			io_callback(&context);
		}
		else
		{
			while (t + expire_time > mtime())
			{
			}
			/* 等待一个偏移 */
			// io_mutex_wait(mutex, cond, expire_time);
		}
	}
	else
	{
	}
	io_mutex_unlock(mutex, cond);
	/* 这里注意如果对文本返回需要看地址是否回收 */
	RETURN_BOOL(TRUE);
}

/**
 * 打印插槽列表
 * 
 * @description: iwonmo
 * @Date: 2021-06-29 16:45:28
 * @param {*}
 * @return {*}
 */
IO_FUNCTION(io_debug_slot_list)
{
	apc_debug_slot_list(cache);
}

/* {{{ iwonmo_functions[]
 *
 * Every user visible function must have an entry in iwonmo_functions[].
 */
const zend_function_entry iwonmo_functions[] = {
	PHP_FE(confirm_iwonmo_compiled, NULL) /* For testing, remove later. */
	PHP_FE(io_interval, NULL)			  /* 间隔函数. */
	PHP_FE(io_mtime, NULL)				  /* 获取毫秒函数. */
	PHP_FE(io_looptext, NULL)			  /* 循环字符串 */
	PHP_FE(io_debug_slot_list, NULL)	  /* 调试 cache 列表 */
	PHP_FE_END							  /* Must be the last line in iwonmo_functions[] */
};
/* }}} */

/* {{{ iwonmo_module_entry
 */
zend_module_entry iwonmo_module_entry = {
	STANDARD_MODULE_HEADER,
	"iwonmo",
	iwonmo_functions,
	PHP_MINIT(iwonmo),
	PHP_MSHUTDOWN(iwonmo),
	PHP_RINIT(iwonmo),	   /* Replace with NULL if there's nothing to do at request start */
	PHP_RSHUTDOWN(iwonmo), /* Replace with NULL if there's nothing to do at request end */
	PHP_MINFO(iwonmo),
	PHP_IWONMO_VERSION,
	STANDARD_MODULE_PROPERTIES};
/* }}} */

#ifdef COMPILE_DL_IWONMO
#ifdef ZTS
ZEND_TSRMLS_CACHE_DEFINE()
#endif
ZEND_GET_MODULE(iwonmo)
#endif

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */